package com.net.xpay.core.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.*;
import com.alipay.api.response.AlipayFundFlexiblestaffingEmployeehomeApplyResponse;
import com.alipay.api.response.AlipayFundFlexiblestaffingEmployeehomeUnsignResponse;
import com.alipay.api.response.AlipayFundFlexiblestaffingRepaymentTransferResponse;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.net.xpay.common.domain.FlexibleStaffCard;
import com.net.xpay.common.domain.User;
import com.net.xpay.common.domain.notify.FlexibleStaffCardNotifyRecord;
import com.net.xpay.common.domain.notify.FlexibleStaffCardOrderNotifyRecord;
import com.net.xpay.common.enums.notify.NotifyStatus;
import com.net.xpay.common.manager.FlexibleStaffCardManager;
import com.net.xpay.common.manager.UserManager;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.service.safePay.FlexibleStaffCardService;
import com.net.xpay.core.validator.FlexibleStaffCardValidator;
import com.net.common.exception.BusinessException;
import com.net.common.util.HttpClientUtil;
import com.net.common.util.LocalDateUtil;
import com.net.common.util.SerializationUtil;
import com.net.xpay.alipay.model.FundFlexiblestaffingEmployeehomeApplyModel;
import com.net.xpay.alipay.safePay.PoseidonSafePayAlipayClient;
import com.net.xpay.alipay.safePay.SafePayAlipayProperties;
import com.net.xpay.common.manager.notify.FlexibleStaffCardNotifyRecordManager;
import com.net.xpay.common.manager.notify.FlexibleStaffCardOrderNotifyRecordManager;
import com.net.xpay.core.domain.FlexibleStaffCardOrder;
import com.net.xpay.core.dto.FlexibleStaffCardDto;
import com.net.xpay.core.dto.FlexibleStaffCardOrderDto;
import com.net.xpay.core.enums.AgreementStatus;
import com.net.xpay.core.enums.BookStatus;
import com.net.xpay.core.enums.FlexibleStaffCardOrderType;
import com.net.xpay.core.helper.SignerCheckHelper;
import com.net.xpay.core.manager.FlexibleStaffCardOrderManager;
import com.net.xpay.core.model.ApplyFlexibleStaffCardModel;
import com.net.xpay.core.model.FlexibleStaffCardRepaymentTransferModel;
import com.net.xpay.core.utils.GenIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class FlexibleStaffCardServiceImpl implements FlexibleStaffCardService {

    @Autowired
    private FlexibleStaffCardManager flexibleStaffCardManager;

    @Autowired
    private PoseidonSafePayAlipayClient xpaySafePayAlipayClient;

    @Autowired
    private FlexibleStaffCardValidator flexibleStaffCardValidator;

    @Autowired
    private SafePayAlipayProperties safePayAlipayProperties;

    @Autowired
    private FlexibleStaffCardNotifyRecordManager flexibleStaffCardNotifyRecordManager;

    @Autowired
    private UserManager userManager;

    @Autowired
    private SignerCheckHelper signerCheckHelper;

    @Autowired
    private FlexibleStaffCardOrderManager flexibleStaffCardOrderManager;

    @Autowired
    private FlexibleStaffCardOrderNotifyRecordManager flexibleStaffCardOrderNotifyRecordManager;

    @Override
    @Transactional(transactionManager = "xpayCommonTransactionManager", rollbackFor = Exception.class)
    public FlexibleStaffCard applyFlexibleStaffCard(User user, ApplyFlexibleStaffCardModel applyModel) {
        flexibleStaffCardValidator.validateApplyFlexibleStaffCard(user, applyModel);

        FlexibleStaffCard card = flexibleStaffCardManager.findByIdentity(user.getId(),
                applyModel.getIdentity(), applyModel.getHireIdentity());

        if (card != null) {
            return reApplyFlexibleStaffCard(user, card, applyModel);
        } else {
            return doApplyFlexibleStaffCard(user, applyModel);
        }

    }

    @Override
    @Transactional(transactionManager = "xpayCommonTransactionManager", rollbackFor = Exception.class)
    public void updateFlexibleStaffCard(String outBizNo, String agreementNo, String alipayUid, String bookId, String employeeCardNo) {
        Preconditions.checkArgument(!Strings.isNullOrEmpty(outBizNo) && !Strings.isNullOrEmpty(alipayUid));
        FlexibleStaffCard card = flexibleStaffCardManager.getByOutBizNo(outBizNo);
        if (card == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "零工卡不存在");
        }

        card.setAlipayUid(alipayUid);
        card.setEmployeeCardNo(employeeCardNo);
        if (!Strings.isNullOrEmpty(bookId)) {
            card.setBookId(bookId);
        }
        if (!Strings.isNullOrEmpty(agreementNo)) {
            card.setAgreementNo(agreementNo);
        }

        card.setBookStatus(BookStatus.YES);
        card.setOpenCardTime(LocalDateTime.now());
        card.setSignTime(LocalDateTime.now());
        card.setAgreementStatus(AgreementStatus.VALID);
        flexibleStaffCardManager.update(card);

        //消息推送
        processNotify(card);
    }

    private void processNotify(FlexibleStaffCard card) {
        if (Strings.isNullOrEmpty(card.getNotifyUrl())) {
            return;
        }
        FlexibleStaffCardNotifyRecord record = new FlexibleStaffCardNotifyRecord();
        record.setUserId(card.getUserId());
        record.setImportBizNo(card.getImportBizNo());
        record.setFlexibleStaffCardId(card.getId());
        record.setStatus(NotifyStatus.WAIT);

        record.setNotifyUrl(card.getNotifyUrl());
        record.setNotifyCount(0);
        record.setNextNotifyTime(LocalDateTime.now());

        FlexibleStaffCardDto dto = new FlexibleStaffCardDto();
        dto.setImportBizNo(card.getImportBizNo());
        dto.setAgreementStatus(card.getAgreementStatus());
        dto.setOpenCardTime(card.getOpenCardTime());
        dto.setBookId(card.getBookId());
        dto.setAlipayUid(card.getAlipayUid());
        dto.setIdentity(card.getIdentity());
        dto.setIdentityType(card.getIdentityType());
        dto.setLoanAgreementNo(card.getAgreementNo());

        record.setNotifyContent(SerializationUtil.obj2String(dto));
        flexibleStaffCardNotifyRecordManager.save(record);

        //直接推送一下 减少延迟
        try {
            notifyRecord(record);
        } catch (Exception e) {
            log.info("processNotify failed|dto={}", SerializationUtil.obj2String(dto), e);
        }
    }

    public void notifyRecord(FlexibleStaffCardNotifyRecord record) {
        if (Strings.isNullOrEmpty(record.getNotifyUrl())) {
            return;
        }
        User user = userManager.getById(record.getUserId());

        List<NameValuePair> paramList = new ArrayList<>();
        NameValuePair appkey = new BasicNameValuePair("appkey", user.getAppkey());
        paramList.add(appkey);
        String time = System.currentTimeMillis() + "";
        NameValuePair timestamp = new BasicNameValuePair("timestamp", time);
        paramList.add(timestamp);
        NameValuePair signature = new BasicNameValuePair("signature", signerCheckHelper.sign(user.getAppkey(), user.getSecret(), time));
        paramList.add(signature);
        NameValuePair data = new BasicNameValuePair("data", record.getNotifyContent());
        paramList.add(data);

        String resp;
        try {
            HttpPost method = new HttpPost(record.getNotifyUrl());
            method.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
            resp = HttpClientUtil.getInstance().executeAndGet(method, null, "UTF-8");
            log.info("notifyRecord|id={}|userId={}|resp={}", record.getImportBizNo(), record.getUserId(), resp);
            if (resp != null && "ok".equalsIgnoreCase(resp.trim())) {
                record.setStatus(NotifyStatus.OK);
                record.setNotifyCount(record.getNotifyCount() + 1);
                record.setEndTime(LocalDateTime.now());
                flexibleStaffCardNotifyRecordManager.update(record);
            } else {
                record.setNotifyCount(record.getNotifyCount() + 1);
                if (record.getNotifyCount() >= 8) {
                    record.setStatus(NotifyStatus.DEAD);
                    record.setEndTime(LocalDateTime.now());
                    flexibleStaffCardNotifyRecordManager.update(record);
                } else {
                    long[] minutes = new long[]{
                            2, 10, 10, 60, 120, 360, 900
                    };
                    record.setNextNotifyTime(record.getNextNotifyTime().plusMinutes(minutes[(record.getNotifyCount() - 1) % 7]));
                    flexibleStaffCardNotifyRecordManager.update(record);
                }
            }
        } catch (Throwable e) {
            log.error("doNotifyRecord error|id={}|userId={}", record.getImportBizNo(), record.getUserId(), e);
            record.setNotifyCount(record.getNotifyCount() + 1);
            if (record.getNotifyCount() >= 8) {
                record.setStatus(NotifyStatus.DEAD);
                record.setEndTime(LocalDateTime.now());
                flexibleStaffCardNotifyRecordManager.update(record);
            } else {
                long[] minutes = new long[]{
                        2, 10, 10, 60, 120, 360, 900
                };
                record.setNextNotifyTime(record.getNextNotifyTime().plusMinutes(minutes[(record.getNotifyCount() - 1) % 7]));
                flexibleStaffCardNotifyRecordManager.update(record);
            }
        }

    }

    @Override
    public void unsignFlexibleStaffCard(User user, String importBizNo) {
        if (Strings.isNullOrEmpty(importBizNo)) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "外部订单号不能为空");
        }
        FlexibleStaffCard card = flexibleStaffCardManager.findByImportBizNo(user.getId(), importBizNo);
        if (card == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "灵工卡不存在");
        }
        if (card.getAgreementStatus() != AgreementStatus.VALID) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "灵工卡已解约");
        }
        AlipayFundFlexiblestaffingEmployeehomeUnsignModel model = new AlipayFundFlexiblestaffingEmployeehomeUnsignModel();
        model.setPrincipalUserId(card.getAlipayUid());
        model.setTargetId(card.getAgreementNo());

        try {
            AlipayFundFlexiblestaffingEmployeehomeUnsignResponse response = xpaySafePayAlipayClient.unsignAlipayFundFlexiblestaffingEmployeehome(model);
            if (!response.isSuccess()) {
                log.info("unsignFlexibleStaffCard failed|model={}|importBizNo={}|msg={}|code={}", SerializationUtil.obj2String(model), importBizNo, response.getMsg() + "|" + response.getSubMsg(), response.getCode() + "|" + response.getSubCode());
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, response.getSubMsg());
            }
            card.setUnSignTime(LocalDateTime.now());
            card.setAgreementStatus(AgreementStatus.INVALID);
            flexibleStaffCardManager.update(card);
        } catch (AlipayApiException e) {
            log.error("unsignFlexibleStaffCard error|importBizNo={}", importBizNo, e);
        }
    }

    @Override
    public void transferRepayment(User user, FlexibleStaffCardRepaymentTransferModel model) {
        flexibleStaffCardValidator.validateTransfer(user, model);

        FlexibleStaffCard card = flexibleStaffCardManager.findByLoanAgreementNo(user.getId(), model.getLoanAgreementNo());
        if (card == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "灵工卡不存在");
        }

        FlexibleStaffCardOrder order = flexibleStaffCardOrderManager.findByImportBizNo(user.getId(), model.getImportBizNo());
        if (order != null) {
            //检查下收款信息变了没有
            if (!order.getIdentity().equals(model.getIdentity()) || !order.getTransAmount().equals(new BigDecimal(model.getTransAmount()))
             || !order.getType().equals(model.getType()) || !order.getLoanAgreementNo().equals(model.getLoanAgreementNo())) {
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "外部订单号已被使用");
            }

            //已完成转账
            if (order.getPayFundOrderId() != null) {
                return;
            }
        } else {
            order = new FlexibleStaffCardOrder();
        }


        order.setUserId(user.getId());
        order.setPartnerId(user.getPartnerId());
        order.setFlexibleStaffCardId(card.getId());
        order.setImportBizNo(model.getImportBizNo());
        order.setType(model.getType());
        order.setLoanAgreementNo(model.getLoanAgreementNo());
        order.setOrderTitle(model.getOrderTitle());
        order.setRemark(model.getRemark());
        order.setTransAmount(new BigDecimal(model.getTransAmount()));
        order.setIdentity(model.getIdentity());
        order.setIdentityType(model.getIdentityType());
        order.setName(model.getName());
        order.setAgreementNo(model.getAgreementNo());
        order.setNotifyUrl(model.getNotifyUrl());

        if (order.getId() == null) {
            flexibleStaffCardOrderManager.save(order);
        } else {
            flexibleStaffCardOrderManager.update(order);
        }

        //调用支付宝接口
        doTransferRepaymentByAlipay(order);
    }

    @Override
    public void onRepaymentTransferNotify(String outBizNo, String orderId, String payFundOrderId) {
        Preconditions.checkArgument(!Strings.isNullOrEmpty(outBizNo) && !Strings.isNullOrEmpty(payFundOrderId));
        FlexibleStaffCardOrder order = flexibleStaffCardOrderManager.getByOutBizNo(outBizNo);
        order.setOrderId(orderId);
        order.setPayFundOrderId(payFundOrderId);
        flexibleStaffCardOrderManager.update(order);

        //推送
        processOrderRecordNotify(order);
    }

    private void processOrderRecordNotify(FlexibleStaffCardOrder order) {
        if (Strings.isNullOrEmpty(order.getNotifyUrl())) {
            return;
        }

        FlexibleStaffCardOrderNotifyRecord record = new FlexibleStaffCardOrderNotifyRecord();
        record.setUserId(order.getUserId());
        record.setImportBizNo(order.getImportBizNo());
        record.setFlexibleStaffCardOrderId(order.getId());
        record.setStatus(NotifyStatus.WAIT);
        record.setNotifyUrl(order.getNotifyUrl());
        record.setNotifyCount(0);
        record.setNextNotifyTime(LocalDateTime.now());

        FlexibleStaffCardOrderDto dto = new FlexibleStaffCardOrderDto();
        dto.setImportBizNo(order.getImportBizNo());
        dto.setEndTime(order.getEndTime());
        dto.setOrderId(order.getOrderId());
        dto.setPayFundOrderId(order.getPayFundOrderId());
        record.setNotifyContent(SerializationUtil.obj2String(dto));

        flexibleStaffCardOrderNotifyRecordManager.save(record);

        try {
            notifyOrderRecord(record);
        } catch (Exception e) {
            log.error("processOrderRecordNotify|notifyContent={}", record.getNotifyContent(), e);
        }
    }

    public void notifyOrderRecord(FlexibleStaffCardOrderNotifyRecord record) {
        if (Strings.isNullOrEmpty(record.getNotifyUrl())) {
            return;
        }
        User user = userManager.getById(record.getUserId());

        List<NameValuePair> paramList = new ArrayList<>();
        NameValuePair appkey = new BasicNameValuePair("appkey", user.getAppkey());
        paramList.add(appkey);
        String time = System.currentTimeMillis() + "";
        NameValuePair timestamp = new BasicNameValuePair("timestamp", time);
        paramList.add(timestamp);
        NameValuePair signature = new BasicNameValuePair("signature", signerCheckHelper.sign(user.getAppkey(), user.getSecret(), time));
        paramList.add(signature);
        NameValuePair data = new BasicNameValuePair("data", record.getNotifyContent());
        paramList.add(data);

        String resp;
        try {
            HttpPost method = new HttpPost(record.getNotifyUrl());
            method.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
            resp = HttpClientUtil.getInstance().executeAndGet(method, null, "UTF-8");
            log.info("notifyOrderRecord|id={}|userId={}|resp={}", record.getImportBizNo(), record.getUserId(), resp);
            if (resp != null && "ok".equalsIgnoreCase(resp.trim())) {
                record.setStatus(NotifyStatus.OK);
                record.setNotifyCount(record.getNotifyCount() + 1);
                record.setEndTime(LocalDateTime.now());
                flexibleStaffCardOrderNotifyRecordManager.update(record);
            } else {
                record.setNotifyCount(record.getNotifyCount() + 1);
                if (record.getNotifyCount() >= 8) {
                    record.setStatus(NotifyStatus.DEAD);
                    record.setEndTime(LocalDateTime.now());
                    flexibleStaffCardOrderNotifyRecordManager.update(record);
                } else {
                    long[] minutes = new long[]{
                            2, 10, 10, 60, 120, 360, 900
                    };
                    record.setNextNotifyTime(record.getNextNotifyTime().plusMinutes(minutes[(record.getNotifyCount() - 1) % 7]));
                    flexibleStaffCardOrderNotifyRecordManager.update(record);
                }
            }
        } catch (Throwable e) {
            log.error("notifyOrderRecord error|id={}|userId={}", record.getImportBizNo(), record.getUserId(), e);
            record.setNotifyCount(record.getNotifyCount() + 1);
            if (record.getNotifyCount() >= 8) {
                record.setStatus(NotifyStatus.DEAD);
                record.setEndTime(LocalDateTime.now());
                flexibleStaffCardOrderNotifyRecordManager.update(record);
            } else {
                long[] minutes = new long[]{
                        2, 10, 10, 60, 120, 360, 900
                };
                record.setNextNotifyTime(record.getNextNotifyTime().plusMinutes(minutes[(record.getNotifyCount() - 1) % 7]));
                flexibleStaffCardOrderNotifyRecordManager.update(record);
            }
        }
    }

    private void doTransferRepaymentByAlipay(FlexibleStaffCardOrder order) {
        AlipayFundFlexiblestaffingRepaymentTransferModel model = new AlipayFundFlexiblestaffingRepaymentTransferModel();
        model.setProductCode("FLEXIBLE_STAFFING_TRANSFER");
        if (order.getType() == FlexibleStaffCardOrderType.REPAY) {
            model.setBizScene("ENTRUST_REPAYMENT");
        } else {
            model.setBizScene("ENTRUST_WITHDRAW");
        }

        model.setOutBizNo(order.getOutBizNo());
        model.setTransAmount(order.getTransAmount().toString());
        model.setLoanAgreementNo(order.getLoanAgreementNo());

        RepaymentParticipant repaymentParticipant = new RepaymentParticipant();
        repaymentParticipant.setIdentity(order.getIdentity());
        repaymentParticipant.setName(order.getName());
        repaymentParticipant.setIdentityType(order.getIdentityType().getValue());

        RepaymentParticipantExtInfo extInfo = new RepaymentParticipantExtInfo();
        extInfo.setAgreementNo(order.getAgreementNo());
        repaymentParticipant.setExtInfo(extInfo);
        model.setPayeeInfo(repaymentParticipant);
        model.setOrderTitle(order.getOrderTitle());
        model.setRemark(order.getRemark());
        try {
            AlipayFundFlexiblestaffingRepaymentTransferResponse response = xpaySafePayAlipayClient.transferAlipayFundFlexiblestaffingRepayment(model);
            if (!response.isSuccess()) {
                log.info("doTransferRepaymentByAlipay failed|model={}|importBizNo={}|msg={}|code={}", SerializationUtil.obj2String(model), order.getImportBizNo(), response.getMsg() + "|" + response.getSubMsg(), response.getCode() + "|" + response.getSubCode());
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, response.getSubMsg());
            }
            order.setPayFundOrderId(response.getFundOrderId());
            order.setEndTime(LocalDateTime.now());
            flexibleStaffCardOrderManager.update(order);
        } catch (AlipayApiException e) {
            log.error("doTransferRepaymentByAlipay error|importBizNo={}", order.getImportBizNo(), e);
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "灵工卡交易失败");
        }
    }

    private FlexibleStaffCard doApplyFlexibleStaffCard(User user, ApplyFlexibleStaffCardModel applyModel) {
        FlexibleStaffCard card = buildCard(user, applyModel);
        alipayApplyFlexibleStaffCard(user, card);
        flexibleStaffCardManager.save(card);
        return card;
    }

    private FlexibleStaffCard buildCard(User user, ApplyFlexibleStaffCardModel applyModel) {
        FlexibleStaffCard card = new FlexibleStaffCard();
        card.setUserId(user.getId());
        card.setIdentity(applyModel.getIdentity());
        card.setIdentityType(applyModel.getIdentityType());
        card.setIdentityName(applyModel.getIdentityName());
        card.setImportBizNo(applyModel.getImportBizNo());
        card.setOutBizNo(GenIdUtil.getId("A", user.getId()));
        card.setBookStatus(BookStatus.NO);
        card.setAgreementStatus(AgreementStatus.INVALID);
        card.setInviterIdentity(safePayAlipayProperties.getIdentity());
        card.setInviterIdentityType("ALIPAY_LOGON_ID");
        card.setInviterIdentityName(safePayAlipayProperties.getIdentityName());
        card.setHireIdentity(applyModel.getHireIdentity());
        card.setHireIdentityType(applyModel.getHireIdentityType());
        card.setHireIdentityName(applyModel.getHireIdentityName());
        card.setHasCapital(0);
        card.setRepaymentAmount(applyModel.getRepaymentAmount());
        card.setRepaymentEndTime(LocalDateUtil.getDateTimeAsString(LocalDateTime.now().plusYears(100L)));
        card.setApplyLinkExpireTime(LocalDateTime.now().plusHours(2L).withSecond(0)
                .withNano(0));
        card.setNotifyUrl(applyModel.getNotifyUrl());
        card.setReturnUrl(applyModel.getReturnUrl());
        return card;
    }

    //支付宝发起开卡请求
    private FlexibleStaffCard alipayApplyFlexibleStaffCard(User user, FlexibleStaffCard card) {
        FundFlexiblestaffingEmployeehomeApplyModel model = new FundFlexiblestaffingEmployeehomeApplyModel();

        model.setOutBizNo(card.getOutBizNo());
        ParticipantInfoDTO participantInfoDTO = new ParticipantInfoDTO();
        participantInfoDTO.setName(card.getIdentityName());
        participantInfoDTO.setParticipantId(card.getIdentity());
        participantInfoDTO.setParticipantIdType(card.getIdentityType());
        model.setPrincipalInfo(participantInfoDTO);
        model.setExpireTime(LocalDateUtil.getDateTimeAsString(card.getApplyLinkExpireTime(), "yyyy-MM-dd HH:mm")); //报时间格式错误

        EmployeeCardInfo employeeCardInfo = new EmployeeCardInfo();
        ParticipantInfoDTO inviter = new ParticipantInfoDTO();
        inviter.setName(card.getInviterIdentityName());
        inviter.setParticipantId(card.getInviterIdentity());
        inviter.setParticipantIdType(card.getInviterIdentityType());
        employeeCardInfo.setInvitePrincipal(inviter);

        ParticipantInfoDTO hirePrincipal = new ParticipantInfoDTO();
        hirePrincipal.setName(card.getHireIdentityName());
        hirePrincipal.setParticipantId(card.getHireIdentity());
        hirePrincipal.setParticipantIdType(card.getHireIdentityType());
        employeeCardInfo.setHirePrincipal(hirePrincipal);

        model.setEmployeeCardInfo(employeeCardInfo);

        RentServiceInfo rentServiceInfo = new RentServiceInfo();
        rentServiceInfo.setRepaymentAmount(card.getRepaymentAmount().toString());
        rentServiceInfo.setRepaymentPeriodType("NATURAL_MONTH");
        rentServiceInfo.setRepaymentEndTime(LocalDateUtil.getDateTimeAsString(LocalDateTime.now().plusYears(100L)));

        rentServiceInfo.setInvitePrincipal(inviter);
        model.setRentAgreementInfo(rentServiceInfo);

        try {
            AlipayFundFlexiblestaffingEmployeehomeApplyResponse resp = xpaySafePayAlipayClient.applyAlipayFundFlexiblestaffingEmployeehome(model, card.getReturnUrl());
            if (!resp.isSuccess()) {
                log.warn("doApplyFlexibleStaffCard failed userId={}|card={}", user.getId(), SerializationUtil.obj2String(card));
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, resp.getSubMsg());
            }
            card.setApplyLink(resp.getApplyLink());
            card.setFlowToken(resp.getFlowToken());
            return card;
        } catch (AlipayApiException e) {
            log.error("doApplyFlexibleStaffCard error|userId={}", user.getId(), e);
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "系统繁忙");
        }
    }

    private FlexibleStaffCard reApplyFlexibleStaffCard(User user, FlexibleStaffCard card, ApplyFlexibleStaffCardModel applyModel) {
        if (card.getAgreementStatus() == AgreementStatus.VALID) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "零工卡已开通");
        }
        card.setIdentity(applyModel.getIdentity());
        card.setIdentityType(applyModel.getIdentityType());
        card.setIdentityName(applyModel.getIdentityName());
        card.setImportBizNo(applyModel.getImportBizNo());
        card.setOutBizNo(GenIdUtil.getId("A", user.getId()));
        card.setInviterIdentity(safePayAlipayProperties.getIdentity());
        card.setInviterIdentityType("ALIPAY_LOGON_ID");
        card.setInviterIdentityName(safePayAlipayProperties.getIdentityName());
        card.setHireIdentity(applyModel.getHireIdentity());
        card.setHireIdentityType(applyModel.getHireIdentityType());
        card.setHireIdentityName(applyModel.getHireIdentityName());
        card.setHasCapital(0);
        card.setRepaymentAmount(applyModel.getRepaymentAmount());
        card.setRepaymentEndTime(LocalDateUtil.getDateTimeAsString(LocalDateTime.now().plusYears(100L)));
        card.setApplyLinkExpireTime(LocalDateTime.now().plusHours(2L).withSecond(0)
                .withNano(0));
        card.setNotifyUrl(applyModel.getNotifyUrl());
        card.setReturnUrl(applyModel.getReturnUrl());
        alipayApplyFlexibleStaffCard(user, card);

        flexibleStaffCardManager.update(card);
        return card;
    }
}
